﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace KgUtils.Web
{
    public static partial class SessionHelper
    {
        public static void SetValueInSession(string key, object value)
        {
            //if the value already exist, it is replaced.
            if (HttpContext.Current.Session != null)
            {
                lock (HttpContext.Current.Session.SyncRoot)
                {
                    HttpContext.Current.Session.Add(key, value);
                }
            }
        }

        public static object GetValueFromSession(string key)
        {
            //returns null if it doesn't exist.
            if (HttpContext.Current.Session != null)
                return HttpContext.Current.Session[key];
            else
                return null;
        }

        public static T GetValueFromSession<T>(string key)
        {
            //returns null if it doesn't exist.
            if (HttpContext.Current.Session != null)
                return (T)HttpContext.Current.Session[key];
            else
                return default(T);
        }

        public static bool IsDefined(string key)
        {
            if (HttpContext.Current.Session != null && HttpContext.Current.Session.Keys != null)
            {
                return HttpContext.Current.Session[key] != null;
            }
            else
            {
                return false;
            }
        }

        public static void Remove(string key)
        {
            lock (HttpContext.Current.Session.SyncRoot)
            {
                HttpContext.Current.Session.Remove(key);
            }
        }

        public static void TryRemove(string key)
        {
            if (HttpContext.Current.Session != null && HttpContext.Current.Session.Keys != null)
            {
                if (SessionHelper.IsDefined(key))
                {
                    SessionHelper.Remove(key);
                }
            }
        }
    }
}
